package com.alpesressources.comexpert.jasper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.sql.Connection;
import java.util.Map;

import org.apache.log4j.Logger;

import com.alpesressources.comexpert.Report;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRRuntimeException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.view.JasperViewer;

public class Jasper {
	private static Logger logger = Logger.getLogger(Jasper.class);
	
	public boolean compileReport(String reportName) {
		try {
			JasperCompileManager.compileReportToFile(reportName + ".jrxml",
					reportName + ".jasper");

			return true;
		} catch (JRException e) {
			logger.error(e);
			return false;
		}
	}

	public JasperPrint fillReport(String reportName, Map<String, Object> map, Connection con) {
		try {
			File reportFile = new File(reportName);
			if (!reportFile.exists()) {
				throw new JRRuntimeException(
						"File "
								+ reportName
								+ " not found. The report design must be compiled first.");
			}

			return JasperFillManager.fillReport(reportName, map, con);
		} catch (Exception e) {
			logger.error(e);
			return null;
		}
	}

	public ByteArrayOutputStream exportPDFReport(JasperPrint jasperPrint) {
		JRPdfExporter exporter = new JRPdfExporter();
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, buffer);

		try {
			exporter.exportReport();
		} catch (JRException e) {
			buffer = null;
			logger.error(e);
		}

		return buffer;
	}

	public ByteArrayOutputStream exportTXTReport(JasperPrint jasperPrint) {
		JRCsvExporter exporter = new JRCsvExporter();
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();

		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, buffer);
		// exporter.setParameter(JRTextExporterParameter.PAGE_WIDTH, 80);
		// exporter.setParameter(JRTextExporterParameter.PAGE_HEIGHT, 500);

		try {
			exporter.exportReport();
		} catch (JRException e) {
			buffer = null;
			logger.error(e);
		}

		return buffer;
	}

	public boolean showReport(JasperPrint jasperPrint) {
		JasperViewer.viewReport(jasperPrint);
		return true;
	}
}
